package br.sc.senai.view;

import java.awt.Dimension;
import java.awt.EventQueue;

import javax.swing.JInternalFrame;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JTextField;
import javax.swing.JRadioButton;
import javax.swing.ButtonGroup;
import javax.swing.JScrollPane;

import javax.swing.Box;
import javax.swing.JTable;
import javax.swing.JButton;
import javax.swing.ImageIcon;

import br.sc.senai.dao.ClienteDAO;
import br.sc.senai.model.Cliente;
import br.sc.senai.model.ClienteTableModel;
import br.sc.senai.model.ForcarSelecaoUnica;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.awt.event.MouseMotionAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

@SuppressWarnings("serial")
public class ConsultarClientesUI extends JInternalFrame {
	private JTextField textField;
	private final ButtonGroup buttonGroup = new ButtonGroup();
	private JTable table = new JTable();
	private ClienteDAO clienteDAO = new ClienteDAO();
	private ArrayList<Cliente> clientes = clienteDAO.consultar();
	private ArrayList<Cliente> clientesFisicos = new ArrayList<Cliente>();
	private ArrayList<Cliente> clientesJuridicos = new ArrayList<Cliente>();
	private final JRadioButton rdbtnFsica;
	private final JRadioButton rdbtnJurdica;

	private static ConsultarClientesUI instancia;

	public static ConsultarClientesUI obterInstancia() {
		if (instancia == null) {
			instancia = new ConsultarClientesUI();
		}
		return instancia;
	}

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			@Override
			public void run() {
				try {
					ConsultarClientesUI frame = new ConsultarClientesUI();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public ConsultarClientesUI() {
		setTitle("Consultar Clientes");
		Dimension d = PrincipalUI.obterInstancia().getSize();
		d.setSize(d.getWidth(), (d.getHeight() - 100));
		setBounds(0, 80, (int) d.getWidth(), (int) d.getHeight());
		this.setMinimumSize(d);

		addMouseMotionListener(new MouseMotionAdapter() {
			@Override
			public void mouseMoved(MouseEvent e) {
				// setLocation(0, 80);
			}
		});
		setClosable(true);
		setResizable(false);

		for (int i = 0; i < clientes.size(); i++) {
			if (clientes.get(i).getCpf() != null) {
				clientesFisicos.add(clientes.get(i));
			} else {
				clientesJuridicos.add(clientes.get(i));
			}
		}

		final JComboBox comboBox = new JComboBox();
		comboBox.setModel(new DefaultComboBoxModel(new String[] { "Nome",
				"CPF/CNPJ" }));

		textField = new JTextField();
		textField.addKeyListener(new KeyAdapter() {
			@Override
			public void keyReleased(KeyEvent e) {
				String s = textField.getText();
				String combo = comboBox.getSelectedItem().toString();
				if (s.isEmpty()) {
					if (rdbtnFsica.isSelected()) {
						try {
							table.setModel(new ClienteTableModel(
									clientesFisicos));
						} catch (Exception e2) {
							table.setModel(new ClienteTableModel());
						}
					} else {
						try {
							table.setModel(new ClienteTableModel(
									clientesJuridicos));
						} catch (Exception e2) {
							table.setModel(new ClienteTableModel());
						}
					}
				} else {
					if (combo == "Nome") {
						if (rdbtnFsica.isSelected()) {
							table.setModel(new ClienteTableModel(clienteDAO
									.consultarPorNomeFisico(clientesFisicos, s)));
						} else {
							table.setModel(new ClienteTableModel(clienteDAO
									.consultarPorNomeJuridico(
											clientesJuridicos, s)));
						}
					} else {
						if (rdbtnFsica.isSelected()) {
							try {
								table.setModel(new ClienteTableModel(clienteDAO
										.consultarPorCPF(clientesFisicos, s)));
							} catch (Exception e2) {
								table.setModel(new ClienteTableModel());
							}
						} else {
							try {
								table.setModel(new ClienteTableModel(clienteDAO
										.consultarPorCNPJ(clientesJuridicos, s)));
							} catch (Exception e2) {
								table.setModel(new ClienteTableModel());
							}
						}
					}
				}
			}
		});
		textField.setColumns(10);

		rdbtnFsica = new JRadioButton("Física");
		rdbtnFsica.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				textField.requestFocus();
				if (textField.getText().isEmpty()) {
					table.setModel(new ClienteTableModel(clientesFisicos));
				} else {
					if (comboBox.getSelectedItem().toString()
							.equalsIgnoreCase("Nome")) {
						table.setModel(new ClienteTableModel(clienteDAO
								.consultarPorNomeFisico(clientesFisicos,
										textField.getText())));
					} else {
						table.setModel(new ClienteTableModel(clienteDAO
								.consultarPorCPF(clientesFisicos,
										textField.getText())));
					}
				}
			}
		});
		rdbtnFsica.setSelected(true);
		buttonGroup.add(rdbtnFsica);

		rdbtnJurdica = new JRadioButton("Jurídica");
		rdbtnJurdica.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				textField.requestFocus();
				if (textField.getText().isEmpty()) {
					table.setModel(new ClienteTableModel(clientesJuridicos));
				} else {
					if (comboBox.getSelectedItem().toString() == "Nome") {
						table.setModel(new ClienteTableModel(clienteDAO
								.consultarPorNomeJuridico(clientesJuridicos,
										textField.getText())));
					} else {
						table.setModel(new ClienteTableModel(clienteDAO
								.consultarPorCNPJ(clientesJuridicos,
										textField.getText())));
					}
				}
			}
		});
		buttonGroup.add(rdbtnJurdica);

		JScrollPane scrollPane = new JScrollPane();

		Box horizontalBox = Box.createHorizontalBox();

		JButton btnIncluir = new JButton("Incluir");
		btnIncluir.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				IncluirClienteUI incluirClienteUI = IncluirClienteUI
						.obterInstancia();
				incluirClienteUI.moveToFront();
				incluirClienteUI.setFocusable(true);
				incluirClienteUI.requestFocus();
				PrincipalUI.obterInstancia().getContentPane()
						.add(incluirClienteUI, 0);
				incluirClienteUI.setVisible(true);
			}
		});
		btnIncluir.setIcon(new ImageIcon(ConsultarClientesUI.class
				.getResource("/br/sc/senai/icones/Check_24x24.png")));

		JButton btnNewButton = new JButton("Editar");
		btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				int itemSelecionado = -1;
				try {
					itemSelecionado = table.getSelectedRow();
					if (itemSelecionado != -1) {
						EditarClienteUI editarClienteUI;
						if (rdbtnFsica.isSelected()) {
							editarClienteUI = EditarClienteUI.obterInstancia(clientesFisicos.get(itemSelecionado));
						}else{
							editarClienteUI = EditarClienteUI.obterInstancia(clientesJuridicos.get(itemSelecionado));
						}
						editarClienteUI.moveToFront();
						editarClienteUI.setFocusable(true);
						editarClienteUI.requestFocus();
						PrincipalUI.obterInstancia().getContentPane()
								.add(editarClienteUI, 0);
						editarClienteUI.setVisible(true);
					} else {
						JOptionPane.showMessageDialog(null,
								"Selecione uma linha para editar. ");
					}
				} catch (Exception e2) {
					JOptionPane.showMessageDialog(null,
							"Selecione uma linha para editar. ");
				}
			}
		});
		btnNewButton.setIcon(new ImageIcon(ConsultarClientesUI.class
				.getResource("/br/sc/senai/icones/editar.png")));
		JButton btnExcluir = new JButton("Excluir");
		btnExcluir.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int itemSelecionado = -1;
				try {
					itemSelecionado = table.getSelectedRow();
					if (itemSelecionado != -1) {
						String[] s = { "Sim", "Não" };
						if (rdbtnFsica.isSelected()) {
							if (JOptionPane.showOptionDialog(
									null,
									"Deseja excluir "
											+ clientesFisicos.get(
													itemSelecionado).getNome()
											+ "?", "Atenção", 1, 1, null, s,
									"Não") == 0) {

								clienteDAO.excluir(clientesFisicos
										.get(itemSelecionado));
								clientesFisicos.remove(itemSelecionado);

								table.setModel(new ClienteTableModel(
										clientesFisicos));

								JOptionPane.showMessageDialog(null,
										"Cliente excluído com sucesso!");
							}

						} else {
							if (JOptionPane.showOptionDialog(
									null,
									"Deseja excluir "
											+ clientesJuridicos.get(
													itemSelecionado).getNome()
											+ "?", "Atenção", 1, 1, null, s,
									"Não") == 0) {
								clienteDAO.excluir(clientesJuridicos
										.get(itemSelecionado));
								clientesJuridicos.remove(itemSelecionado);

								table.setModel(new ClienteTableModel(
										clientesJuridicos));

								JOptionPane.showMessageDialog(null,
										"Cliente excluído com sucesso!");
							}
						}
					} else {
						JOptionPane.showMessageDialog(null,
								"Selecione uma linha para excluir. ");
					}

				} catch (Exception e2) {
					JOptionPane.showMessageDialog(null,
							"Selecione uma linha para excluir. ");
				}
			}
		});
		btnExcluir.setIcon(new ImageIcon(ConsultarClientesUI.class
				.getResource("/br/sc/senai/icones/Delete_24x24.png")));

		JButton btnSaor = new JButton("Fechar");
		btnSaor.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				dispose();
			}
		});
		btnSaor.setIcon(new ImageIcon(ConsultarClientesUI.class
				.getResource("/br/sc/senai/icones/Undo_24x24.png")));
		GroupLayout groupLayout = new GroupLayout(getContentPane());
		groupLayout
				.setHorizontalGroup(groupLayout
						.createParallelGroup(Alignment.LEADING)
						.addGroup(
								groupLayout
										.createSequentialGroup()
										.addContainerGap()
										.addComponent(btnIncluir)
										.addGap(18)
										.addComponent(btnNewButton)
										.addGap(18)
										.addComponent(btnExcluir)
										.addPreferredGap(
												ComponentPlacement.RELATED,
												584, Short.MAX_VALUE)
										.addComponent(btnSaor)
										.addContainerGap())
						.addGroup(
								Alignment.TRAILING,
								groupLayout
										.createSequentialGroup()
										.addGap(23)
										.addGroup(
												groupLayout
														.createParallelGroup(
																Alignment.TRAILING)
														.addComponent(
																scrollPane,
																Alignment.LEADING,
																GroupLayout.DEFAULT_SIZE,
																973,
																Short.MAX_VALUE)
														.addGroup(
																groupLayout
																		.createSequentialGroup()
																		.addComponent(
																				comboBox,
																				GroupLayout.PREFERRED_SIZE,
																				GroupLayout.DEFAULT_SIZE,
																				GroupLayout.PREFERRED_SIZE)
																		.addGap(18)
																		.addComponent(
																				textField,
																				GroupLayout.PREFERRED_SIZE,
																				619,
																				GroupLayout.PREFERRED_SIZE)
																		.addGap(30)
																		.addComponent(
																				rdbtnFsica)
																		.addGap(18)
																		.addComponent(
																				rdbtnJurdica,
																				GroupLayout.DEFAULT_SIZE,
																				131,
																				Short.MAX_VALUE)
																		.addPreferredGap(
																				ComponentPlacement.RELATED)
																		.addComponent(
																				horizontalBox,
																				GroupLayout.PREFERRED_SIZE,
																				GroupLayout.DEFAULT_SIZE,
																				GroupLayout.PREFERRED_SIZE)))
										.addGap(18)));
		groupLayout
				.setVerticalGroup(groupLayout
						.createParallelGroup(Alignment.LEADING)
						.addGroup(
								groupLayout
										.createSequentialGroup()
										.addGroup(
												groupLayout
														.createParallelGroup(
																Alignment.LEADING)
														.addGroup(
																groupLayout
																		.createSequentialGroup()
																		.addContainerGap()
																		.addGroup(
																				groupLayout
																						.createParallelGroup(
																								Alignment.BASELINE)
																						.addComponent(
																								comboBox,
																								GroupLayout.PREFERRED_SIZE,
																								GroupLayout.DEFAULT_SIZE,
																								GroupLayout.PREFERRED_SIZE)
																						.addComponent(
																								textField,
																								GroupLayout.PREFERRED_SIZE,
																								GroupLayout.DEFAULT_SIZE,
																								GroupLayout.PREFERRED_SIZE)
																						.addComponent(
																								rdbtnJurdica)
																						.addComponent(
																								rdbtnFsica)))
														.addComponent(
																horizontalBox,
																GroupLayout.PREFERRED_SIZE,
																42,
																GroupLayout.PREFERRED_SIZE))
										.addGap(12)
										.addComponent(scrollPane,
												GroupLayout.DEFAULT_SIZE, 484,
												Short.MAX_VALUE)
										.addGap(18)
										.addGroup(
												groupLayout
														.createParallelGroup(
																Alignment.BASELINE)
														.addComponent(
																btnIncluir)
														.addComponent(
																btnNewButton)
														.addComponent(
																btnExcluir)
														.addComponent(btnSaor))
										.addContainerGap()));

		table.setSelectionModel(new ForcarSelecaoUnica());
		table.setModel(new ClienteTableModel(clientesFisicos));
		table.getTableHeader().setResizingAllowed(false);
		table.getTableHeader().setReorderingAllowed(false);
		scrollPane.setViewportView(table);
		getContentPane().setLayout(groupLayout);

	}
}
